package com.cqjtu.store.swiper.service.impl;

import cn.hutool.core.io.FileUtil;

import cn.hutool.core.util.StrUtil;
import com.cqjtu.store.common.*;
import com.cqjtu.store.swiper.mapper.SwiperMapper;
import com.cqjtu.store.swiper.pojo.dto.BaseRequest;
import com.cqjtu.store.swiper.pojo.dto.SwiperDTO;
import com.cqjtu.store.swiper.pojo.entity.Swiper;
import com.cqjtu.store.swiper.pojo.vo.SwiperVO;
import com.cqjtu.store.swiper.service.SwiperService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: cqjtu-store
 * @Titile: SwiperServiceImpl
 * @Author: Lucky
 * @Description: 商品业务层
 */
@Service
public class SwiperServiceImpl implements SwiperService {
    @Autowired
    SwiperMapper swiperMapper;
    final String savePath = System.getProperty("user.dir") + File.separator +
            "cqjtu-store" + File.separator +
            "store-project" + File.separator +
            "src" + File.separator +
            "main" + File.separator +
            "resources" + File.separator +
            "static" + File.separator +
            "images/";

    @Override
    public R<String> upload(MultipartFile avatar) {

        //获取文件的名称（全名称，包括后缀）
        String filename = avatar.getOriginalFilename();
        long flag = System.currentTimeMillis();
        String filePath = savePath + flag + "-" + filename;
        //上传
        File saveFile = new File(filePath);
        try {
            FileUtil.mkParentDirs(filePath);
            avatar.transferTo(saveFile);
            String url = "http://localhost:9080/api/swiper/download/" + flag;

            if (filename.endsWith("png") || filename.endsWith("pdf") || filename.endsWith("jpg")) {
                url += "?&play=1";
            }
            return R.ok(url);
        } catch (IOException e) {
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "文件上传失败");
        }
    }

    @Override
    public void save(SwiperDTO swiperDTO) {
        //将头像的路径持久化到数据库去
        Swiper swiper = new Swiper();
        swiper.setImg_file(swiperDTO.getImg_file());
        swiper.setPriority(swiperDTO.getPriority());
        int result = swiperMapper.saveAvatar(swiper);

        if (result != 1) { //为了模拟数据事务回滚
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "轮播图数据保存数据库失败");
        }
    }

    @Override
    public void download(String flag, String play, HttpServletResponse response) {
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(savePath);
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                String realName = fileName.substring(fileName.indexOf("-") + 1);
                if ("1".equals(play)) {
                    response.addHeader("Content-Disposition", "inline;filename" + URLEncoder.encode(realName, "UTF-8"));
                } else {
                    response.addHeader("Content-Disposition", "attachment;filename" + URLEncoder.encode(realName, "UTF-8"));
                }
                byte[] bytes = FileUtil.readBytes(savePath + fileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public PageInfo<SwiperVO> page(BaseRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<SwiperVO> swiperVOS = swiperMapper.listByCondition(pageRequest);
        return new PageInfo<>(swiperVOS);
    }

    @Override
    public SwiperVO getById(Integer id) {
        if(id==null){
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"轮播图编号不能为空");
        }
        Swiper swiper= swiperMapper.getById(id);
        SwiperVO swiperVO = new SwiperVO();
        swiperVO.setId(swiper.getId());
        swiperVO.setPriority(swiper.getPriority());
        swiperVO.setImg_file(swiper.getImg_file());
        swiperVO.setModify_time(swiper.getModify_time());
        return swiperVO;
    }

    @Override
    public void update(SwiperDTO swiperDTO) {
        if(swiperDTO==null){
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"轮播图不能为空");
        }
        Integer result=swiperMapper.update(swiperDTO);
        if (result != 1) { //为了模拟数据事务回滚
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "轮播图更新数据库失败");
        }
    }

    @Override
    public void delete(Integer id) {
        if(id==null){
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"轮播图编号不能为空");
        }
        Integer result= swiperMapper.delete(id);
        if (result != 1) { //为了模拟数据事务回滚
            throw new ServiceException(ServiceCode.ERR_DELETE_FAILED, "轮播图删除失败");
        }

    }

    @Override
    public List<SwiperVO> getList() throws IOException {
        String path=".\\cqjtu-store\\store-project\\src\\main\\resources\\static\\SwiperNum.txt";

        BufferedReader br = new BufferedReader(new FileReader(path));
        String line = br.readLine();
        int num = Integer.parseInt(line);
        br.close();
        List<Swiper> swiperList = swiperMapper.getList(num);
        List<SwiperVO> swiperVOList= new ArrayList<>();
        swiperList.forEach(swiper -> {
            SwiperVO swiperVO = new SwiperVO();
            swiperVO.setImg_file(swiper.getImg_file());
            swiperVOList.add(swiperVO);
        });
        return swiperVOList;
    }

    @Override
    public Integer getSwiperNum() throws IOException {
        String path=".\\cqjtu-store\\store-project\\src\\main\\resources\\static\\SwiperNum.txt";

        BufferedReader br = new BufferedReader(new FileReader(path));
        String line = br.readLine();
        int num = Integer.parseInt(line);
        return num;
    }

    @Override
    public void modifySwiperNum(int num) throws IOException {
        String path=".\\cqjtu-store\\store-project\\src\\main\\resources\\static\\SwiperNum.txt";
        PrintWriter pw = new PrintWriter(path, "UTF-8");
        pw.println(num);
        pw.close();
    }
}
